package com.urbanski.clipboard.client.action;

import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ClipboardClient;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.message.DisconnectMessage;
import com.urbanski.util.logging.LoggingUtil;

public class DisconnectActionHandler extends ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(DisconnectActionHandler.class);
	
	private String server;
	
	public DisconnectActionHandler(String[] tokens)
	{
		super(ClientCommand.DISCONNECT, tokens);
	}

	@Override
	public void execute()
	{
		processArgs();
		
		if (server != null)
		{
			ServerConnection serverConnection = ClipboardClient.findConnection(server);
			if (serverConnection != null)
			{
				try
				{
					serverConnection.sendMessage(new DisconnectMessage());
				}
				catch (IOException e)
				{
					LoggingUtil.logAndPrintError(LOGGER, "Error sending disconnect message", e);
				}
			}
			ClipboardClient.disconnect(server);
		}
	}
	
	private void processArgs()
	{
		if (tokens.length != 2)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Invalid number of arguments for disconnect command");
			return;
		}
		
		server = tokens[1];
	}
}
